package cn.tedu.boyou.website.controller;

import cn.tedu.boyou.acticle.domain.Destination;
import cn.tedu.boyou.acticle.domain.StrategyDetail;
import cn.tedu.boyou.acticle.domain.Travel;
import cn.tedu.boyou.acticle.domain.TravelContent;
import cn.tedu.boyou.acticle.service.IDestinationService;
import cn.tedu.boyou.acticle.service.IStrategyCatalogService;
import cn.tedu.boyou.acticle.service.IStrategyDetailService;
import cn.tedu.boyou.acticle.service.ITravelService;
import cn.tedu.boyou.acticle.vo.TravelStatisVO;
import cn.tedu.boyou.cache.prefix.TravelStatisKeyPrefix;
import cn.tedu.boyou.cache.service.ITravelStatisRedisService;
import cn.tedu.boyou.comment.domain.TravelComment;
import cn.tedu.boyou.comment.service.IStrategyCommentService;
import cn.tedu.boyou.comment.service.ITravelCommentService;
import cn.tedu.boyou.common.query.TravelCommentQuery;
import cn.tedu.boyou.common.query.TravelQuery;
import cn.tedu.boyou.common.util.AjaxResult;
import cn.tedu.boyou.member.domain.UserInfo;
import cn.tedu.boyou.website.annotation.RequireLogin;
import cn.tedu.boyou.website.annotation.UserParam;
import cn.tedu.boyou.website.util.UMEditorUploader;
import cn.tedu.boyou.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IStrategyCatalogService strategyCatalogService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyCommentService strategyCommentService;

    @Value("${file.path}")
    private String filePath;

    @RequestMapping("")
    public String travels(Model model, @ModelAttribute("qo")TravelQuery qo){
        qo.setState(Travel.STATE_RELEASE);
        model.addAttribute("pageInfo",travelService.query(qo));
        //tcs
        model.addAttribute("tcs",travelCommentService.getCommentByTop5());
        //旅游攻略strategyDetail
        List<StrategyDetail> list = strategyDetailService.getDetailTop5();
        model.addAttribute("details",list);
        return "travel/list";
    }

    @RequestMapping("/detail")
    public String detail(Model model,Long id){
        //detail
        Travel detail = travelService.get(id);
        TravelContent travelContent = travelService.getContent(detail.getId());
        detail.setTravelContent(travelContent);

        model.addAttribute("detail",detail);
        //toasts         //临时关闭
//        List<Destination> toasts = destinationService.getToasts(detail.getDest().getId());
//        toasts.remove(toasts.size()-1);
//        model.addAttribute("toasts",toasts);
        
        //sds 阅读量前3攻略明细
        List<StrategyDetail> sds =  strategyDetailService.getReadTop3(detail.getDest().getId());
        model.addAttribute("sds",sds);
        //ts 阅读量前3的游记
        List<Travel> ts = travelService.getHotReadTop3(detail.getDest().getId());
        model.addAttribute("ts",ts);

        //list 评论列表
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setPageSize(Integer.MAX_VALUE);
        Page<TravelComment> page = travelCommentService.query(qo);
        model.addAttribute("list",page.getContent());


        //页面加载的时候就发送请求让当前的文章的阅读数对应的加1.
        travelStatisRedisService.viewIncrease(TravelStatisKeyPrefix.TRAVEL_STATIS_VO,id);
        TravelStatisVO travelVo = travelStatisRedisService.getTravelVo(id);
        model.addAttribute("viewnum",travelVo.getViewnum());
        model.addAttribute("favornum",travelVo.getFavornum());
        return "travel/detail";
    }

    @RequestMapping("/input")
    @RequireLogin
    public String input(Model model,Long id){
        if(id != null){
            Travel travel = travelService.get(id);
            TravelContent travelContent = travelService.getContent(travel.getId());
            travel.setTravelContent(travelContent);
            System.err.println(travel.getTravelContent().getContent()+"--------------");
            model.addAttribute("tv",travel);
        }
        List<Destination> list = destinationService.getDestByDeep(3);
        model.addAttribute("regions",list);
        return "/travel/input";
    }

    @RequestMapping("/saveOrUpdate")
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo){
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setData(id);
        return ajaxResult;
    }

    //上传图片
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic){
        String upload = UploadUtil.upload(pic, filePath);
        return upload;
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile,HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    @Reference
    private ITravelCommentService travelCommentService;

    @RequestMapping("/commentAdd")
    public String commentAdd(Model model,TravelComment travelCommend,int floor,@UserParam UserInfo userInfo){
        travelCommend.setUserId(userInfo.getId());
        travelCommend.setUsername(userInfo.getNickname());
        travelCommend.setLevel(userInfo.getLevel());
        travelCommend.setHeadUrl(userInfo.getHeadImgUrl());
        //c
        TravelComment c = travelCommentService.save(travelCommend);
        //floor
        model.addAttribute("floor",floor + 1);
        model.addAttribute("c",c);
        return "travel/commentTpl";
    }

    @Reference
    private ITravelStatisRedisService travelStatisRedisService;
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object travelThumbup(Model model,Long travelId,@UserParam UserInfo userInfo){
        if(userInfo == null){
            return new AjaxResult("请先登录",AjaxResult.CODE_TYPE_UNLOGIN);
        }
        boolean ret = travelStatisRedisService.thumbup(TravelStatisKeyPrefix.TRAVEL_STATIS_THUMBSUP,travelId,userInfo.getId());
        TravelStatisVO travelVo = travelStatisRedisService.getTravelVo(travelId);
        return new AjaxResult(ret,"").addData(travelVo.getThumbsupnum());
    }
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long tid,@UserParam UserInfo userInfo){
        if(userInfo == null){
            return new AjaxResult("登录后才能执行此操作喔",AjaxResult.CODE_TYPE_UNLOGIN);
        }
        boolean ret = travelStatisRedisService.favor(TravelStatisKeyPrefix.TRAVEL_STATIS_FAVOR,tid,userInfo.getId());
        TravelStatisVO travelVo = travelStatisRedisService.getTravelVo(tid);
        return new AjaxResult(ret,"").addData(travelVo);
    }

    @RequestMapping("/detailThumbup")
    @ResponseBody
    public Object detailThumbup(Long tid,@UserParam UserInfo userInfo){
        if(userInfo == null){
            return new AjaxResult("请先登录",AjaxResult.CODE_TYPE_UNLOGIN);
        }
        boolean ret = travelStatisRedisService.thumbup(TravelStatisKeyPrefix.TRAVEL_STATIS_THUMBSUP,tid,userInfo.getId());
        TravelStatisVO travelVo = travelStatisRedisService.getTravelVo(tid);
        return new AjaxResult(ret,"").addData(travelVo);
    }
}
